﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Annual_faculty_promotions.Core.Domain.User;
using Annual_faculty_promotions.Service.Contracts;
using Annual_faculty_promotions.WebUI.Helpers.Filters;
using Annual_faculty_promotions.WebUI.Models;
using Microsoft.AspNet.Identity;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Annual_faculty_promotions.WebUI.Areas.UserArea.Controllers
{
    public class RolesAdminController : Controller
    {

        private readonly IApplicationRoleManager _roleManager;
        private readonly IApplicationUserManager _userManager;
        private readonly IUserService _userService;
        public RolesAdminController(IApplicationUserManager userManager,
                                    IApplicationRoleManager roleManager,
                                    IUserService userService)
        {
            _userManager = userManager;
            _roleManager = roleManager;
            _userService = userService;
        }

        public ActionResult Index()
        {
            return View();
        }


        public ActionResult GetRoles(int page = 1, int pageSize = 10)
        {
            var roles = _roleManager.GetAllCustomRolesAsQueryable()
                .OrderBy(x => x.Id)
                .Skip((page - 1) * pageSize)
                .Take(pageSize);

            JArray ja = new JArray();

            foreach (var item in roles)
            {
                var itemObject = new JObject
                {
                    {"Id",item.Id},
                    {"Name",item.Name},
                    {"PersianName",item.PersianName}   
                };
                ja.Add(itemObject);
            }

            JObject jo = new JObject();
            jo.Add("total", _roleManager.GetAllCustomRolesAsQueryable().Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }



        public ActionResult DatalistRole(int uid)
        {
            var roles = _roleManager.GetAllCustomRolesAsQueryable().ToList();
            var userrole = _roleManager.GetAllCustomUserRole().Where(x=>x.UserId==uid).ToList();
            JArray ja = new JArray();

            foreach (var item in roles)
            {
                var itemObject = new JObject
                {
                    {"id",item.Id},
                    {"Name",item.Name},
                    {"text",item.PersianName},
                };

                foreach (var itm in userrole)
                {
                    if (item.Id == itm.RoleId)
                        itemObject.Add("checked", "True");
                }

                ja.Add(itemObject);
            }

  

            JObject jo = new JObject();
            jo.Add("total", _roleManager.GetAllCustomRolesAsQueryable().Count());
            jo.Add("rows", ja);
            return Content(JsonConvert.SerializeObject(jo), "application/json");
        }
     

        //
        // POST: /Roles/Create
        [HttpPost]
        public async Task<ActionResult> Create(RoleViewModel roleViewModel)
        {
            if (ModelState.IsValid)
            {
                var role = new CustomRole(roleViewModel.Name,roleViewModel.PersianName);
                var roleresult = await _roleManager.CreateAsync(role);
                if (!roleresult.Succeeded)
                {
                    return Json(new { success = true, Msg = roleresult.Errors.First() });
                }
                return Json(new { success = true, Msg = "ثبت شد" });
            }
            return Json(new { success = false, Msg = "ورودی نامعتبر" });
        }


        [HttpPost]
        [AjaxOnly]
        public async Task<ActionResult> Delete(int? id, string deleteUser)
        {
            if (ModelState.IsValid)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                var role = await _roleManager.FindByIdAsync(id.Value);
                if (role == null)
                {
                    return HttpNotFound();
                }
                IdentityResult result;
                if (deleteUser != null)
                {
                    result = await _roleManager.DeleteAsync(role);
                }
                else
                {
                    result = await _roleManager.DeleteAsync(role);
                }
                if (!result.Succeeded)
                {
                    return Json(new { success = false, Msg = result.Errors.First() });
                }
                return Json(new { success = true, Msg = "حذف شد" });
            }
            return Json(new { success = false, Msg = "ورودی نامعتبر" });
        }


        //
        // GET: /Roles/Edit/Admin
        //public async Task<ActionResult> Edit(int? roleId)
        //{
        //    if (roleId == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    var role = await _roleManager.FindByIdAsync(roleId.Value);
        //    if (role == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    RoleViewModel roleModel = new RoleViewModel { Id = role.Id, Name = role.Name,PersianName = role.PersianName};
        //    return PartialView("_Edit", roleModel);
        //}

        //
        // POST: /Roles/Edit/5
        [HttpPost]
        [AjaxOnly]
        public async Task<ActionResult> Edit(RoleViewModel roleModel)
        {
            if (ModelState.IsValid)
            {
                var role = await _roleManager.FindByIdAsync(roleModel.Id);
                role.Name = roleModel.Name;
                role.PersianName = roleModel.PersianName;
                await _roleManager.UpdateAsync(role);
                return Json(new { success = true, Msg = "تغییرات اعمال شد" });
            }
            return Json(new { success = false, Msg = "ورودی نامعتبر" });
        }


       

    }
}